package com.taotao.search.dao.ipml;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.Item;
import com.taotao.common.pojo.SearchResult;
import com.taotao.search.dao.ISolrDao;

@Service
public class SolrDaoIpml implements ISolrDao {

	@Autowired
	private SolrServer server;

	/**
	 * 通过查询条件查询商品信息
	 */
	public SearchResult search(SolrQuery query) throws Exception {
		// TODO Auto-generated method stub
		QueryResponse response = server.query(query);
		SolrDocumentList solrDocumentList = response.getResults();
		List<Item> items = new ArrayList<Item>();
		SearchResult result = new SearchResult();
		long recordCount = solrDocumentList.getNumFound();
		// 获取高亮
		Map<String, Map<String, List<String>>> highlighting = response
				.getHighlighting();
		for (SolrDocument solrDocument : solrDocumentList) {
			// 创建一商品对象
			Item item = new Item();
			item.setId((String) solrDocument.get("id"));
			// 取高亮显示的结果
			String title = "";
			if (highlighting != null) {
				List<String> list = highlighting.get(solrDocument.get("id"))
						.get("item_title");
				if (list != null && list.size() > 0) {
					title = list.get(0);
				} else {
					title = (String) solrDocument.get("item_title");
				}
			}
			item.setTitle(title);
			item.setImage((String) solrDocument.get("item_image"));
			item.setPrice((Long) solrDocument.get("item_price"));
			item.setSell_point((String) solrDocument.get("item_sell_point"));
			item.setCategory_name((String) solrDocument
					.get("item_category_name"));
			// 添加的商品列表
			items.add(item);

		}
		result.setItemList(items);
		result.setRecordCount(recordCount);
		return result;
	}
}
